<?php

class User_Model extends A1_User_Model implements Acl_Role_Interface {

	protected $ignored_columns = array('captcha', 'email_confirm', 'password_confirm');
	protected $has_one = array('user_detail');

	public function get_role_id()
	{
		return $this->role;
	}

	/**
	 * Validates and optionally saves a new user record from an array.
	 *
	 * @param  array    values to check
	 * @param  boolean  save the record when validation succeeds
	 * @return boolean
	 */
	public function validate(array & $array, $save = FALSE)
	{
		$array = Validation::factory($array)
			->pre_filter('trim')
			->add_rules('username', 'required', 'length[4,32]', 'chars[\pL\pN ]', array($this, 'username_available'), array($this, 'has_letters'))
			->add_rules('password', 'length[5,42]')
			->add_rules('email', 'email', 'required')
			->add_rules('email_confirm', 'matches[email]')
			->add_rules('password_confirm', 'matches[password]');

		if (!Captcha::instance()->promoted())
			$array->add_rules('captcha', 'required', 'Captcha::valid');
			//->add_rules('role','matches[user,admin]');

		if ( ! $this->loaded)
		{
			// This user is new, the password must be provided
			$array->add_rules('password', 'required');
		}

		return parent::validate($array, $save);
	}

	public function has_letters($username)
	{
		return (bool)preg_match('/\pL/', $username);
	}

	public function activate() {
		$this->activated = TRUE;
		$this->confirm_code = NULL;
		$this->save();
	}

	public function recovery_pass() {
		if (is_null($this->new_password)) return FALSE;
		return $this->db->update($this->table_name, array('password'=>$this->new_password, 'new_password'=>NULL, 'confirm_code'=>NULL), array($this->primary_key => $this->primary_key_value));
	}

	public function __set($key, $value)
	{
		if ($key === 'new_password')
		{
			// Use Auth to hash the password
			$value = A1::instance($this->config_name)->hash_password($value);
		}

		parent::__set($key, $value);
	}

	public function avatar($size = NULL) {
		$gr = Gravatar::factory($this->email);
		if ($size)
			return $gr->size($size)->render();
		else return $gr->render();
	}

} // End User Model